package com.example.test001.web;


import com.example.test001.dao.RolePermissionMapper;
import com.example.test001.dao.SysMenuMapper;
import com.example.test001.model.RolePermissionKey;
import com.example.test001.model.SysMenu;
import com.example.test001.model.User;
import com.example.test001.model.ztree.From;
import com.example.test001.service.UserService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.*;

@Slf4j
@Controller
@RequestMapping(value = "/menu")
public class MenuController {


    Map<Integer, SysMenu> map = new HashMap<>();

    @Autowired
    private SysMenuMapper sysMenuMapper;


    @Autowired
    private UserService userService;

    @Autowired
    RolePermissionMapper rolePermissionMapper;


    @ResponseBody
    @CrossOrigin
    @PostMapping(value = "/set")
    public void set(@RequestBody From f, HttpServletResponse response) throws IOException {
        List<SysMenu> sysMenus = f.getListKey();


        if (sysMenus.size() == 0) {
            try {
                throw new Exception("未改变");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        RolePermissionKey permissionKey = new RolePermissionKey();
        permissionKey.setRid(1);
        rolePermissionMapper.deleteByPrimaryKey(permissionKey);

        for (SysMenu sysMenu : sysMenus) {
            permissionKey = new RolePermissionKey(1, sysMenu.getMenuId());
            rolePermissionMapper.insert(permissionKey);
        }

        f.getListKey().stream().forEach(System.out::println);
        response.sendRedirect("/menu/alls");

    }


    @ResponseBody
    @CrossOrigin
    @GetMapping("/alls")
    public Object get() {

        List<SysMenu> sysMenus = sysMenuMapper.getAll();

        List<SysMenu> sysMenus1 = userService.getPermissionById(1);

        for (SysMenu sysMenu : sysMenus1) {
            for (SysMenu s : sysMenus) {
                if (sysMenu.getMenuId().equals(s.getMenuId()))
                    s.setChecked(true);
            }
        }

        return sysMenus;

    }


}



























